package com.blb.zycommunity.config;

import com.blb.zycommunity.entity.ResponseResult;
import com.blb.zycommunity.service.ISysUserService;
import com.blb.zycommunity.utils.JwtUtils;
import com.blb.zycommunity.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 登录成功处理器
 */
@RestController
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ISysUserService userService;

    //验证成功后的回调
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //获取登录后的用户名
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            throw new RuntimeException("用户为空");
        }
        //将用户名转换为jwt token
        String token = JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        //将token发送给前端
        ResponseResult.write(ResponseResult.ok(token), httpServletResponse);
    }
}